<template>
  <div>
    <van-search @input="searchfn" shape="round" v-model.trim="value" placeholder="请输入搜索关键词" />
  <template v-if="value === ''">
        <van-cell title="热门搜索" />
    <div style="padding:10px 16px">
      <van-tag @click="tagchange(obj.first)" color="red" round type="primary" size="large" v-for="(obj,index) in hot" :key="index">{{obj.first}}</van-tag>
    </div>
  </template>
   <template v-else>
      <van-cell title="最佳匹配" />
    <van-list
    :immediate-check='false'
    error-text="已经拉到底了"
    :error.sync="iserror"
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="onLoad"
>
    <music-item :row="obj" v-for="obj in list" :key="obj.id"></music-item>

</van-list>
   </template>
  </div>

</template>

<script>
import { searchkeywords, hotsearch } from '@/api/search'
import MusicItem from '../../components/MusicItem.vue'

export default {
  components: { MusicItem },
  created () {
    this.searchhotlist()
  },
  data () {
    return {
      value: '',
      list: [],
      loading: false,
      limit: 20,
      page: 1,
      finished: false,
      iserror: false,
      count: 0,
      hot: []
    }
  },
  methods: {
    tagchange (val) {
      this.value = val
      this.searchfn()
    },

    async searchhotlist () {
      const res = await hotsearch()
      this.hot = res.data.result.hots
    },
    searchfn () {
      this.list = []
      this.finished = false
      this.page = 1
      clearTimeout(this.id)
      if (this.value === '') return (this.finished = true)
      this.loading = true
      this.id = setTimeout(() => {
        this.onLoad()
      }, 700)
    },
    async onLoad () {
      // 异步更新数据
      try {
        const res = await searchkeywords({
          keywords: this.value,
          limit: this.limit,
          offset: (this.page - 1) * this.limit
        })
        console.log(res)
        if (res.data.result.songs) {
          this.list.push(...res.data.result.songs)
          this.count = res.data.result.songCount
          this.page++
        } else {
          this.finished = true
        }
      } catch (error) {
        this.iserror = true
      }
      this.loading = false
      if (this.list.length >= this.count) {
        this.finished = true
      }
      // 1.模拟请求数据
      // 2.保存请求回来的数据
      // 3.加载完成 将加载状态改为false
      // 4.判断是否数据加载完所有
    }
  }
}
</script>

<style>

</style>
